<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.storeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >添加商品</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="roleList">
      <el-table-column label="门店名称" prop="storeName" width="180" />
      <el-table-column label="商品名称" prop="goodsName" />
      <el-table-column label="商品分类" prop="categoryName" />
      <el-table-column label="商品头图" prop="cover">
        <template slot-scope="scope">
          <el-image
            style="width: 40px; height: 40px"
            :src="scope.row.goodsPhoto"
            fit="cover"
            :preview-src-list="[scope.row.goodsPhoto]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="可用库存">
        <template slot-scope="scope">
          {{ scope.row.stockNum }}
        </template>
      </el-table-column>
      <el-table-column label="库存变化">
        <template slot-scope="scope">
          <el-button type="text" @click="openInventoryDialog(scope.row)"
            >库存明细</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <div class="operate-box">
            <el-button type="text" @click="handleEdit(scope.row)"
              >库存调整</el-button
            >
            |
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="库存调整"
      :visible.sync="dialogVisible"
      width="600px"
      append-to-body
      custom-class="custom-dialog" :close-on-click-modal="false"
    >
      <el-form
        ref="dialogFormRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="归属门店：" prop="storeId">
          <!-- 管理员可选，不是管理员就禁用 -->
          <el-select
            v-model="form.storeId"
            :disabled="disabled"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.storeName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调整商品：">
          <el-button type="primary" @click="openSelectProduct"
            >选择商品</el-button
          >
          <div>已选商品：</div>
          <el-table :data="selectProductList">
            <el-table-column label="商品">
              <template slot-scope="scope">
                <div class="flex items-center">
                  <el-image
                    style="width: 40px; height: 40px; margin-right: 12px"
                    :src="scope.row.goodsPhoto"
                    fit="cover"
                  ></el-image>
                  {{ scope.row.goodsName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" @click="handleRemove(scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div>可用库存：{{ stockNum }}</div>
        </el-form-item>
        <el-form-item label="库存变化类型：" prop="changeType">
          <el-radio-group v-model="form.changeType">
            <el-radio
              v-for="dict in dict.type.stock_type"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="变化数量：" prop="stockNum">
          <el-input
            v-number-input
            v-model="form.stockNum"
            placeholder="请输入变化数量"
            maxlength="5"
          />
        </el-form-item>
        <el-form-item label="备注说明：" prop="remark">
          <el-input v-model="form.remark" maxlength="20" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm('dialogFormRef')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 选择商品弹窗 -->
    <select-product-dialog
      ref="selectProductRef"
      @handle-select="handleSelectProduct"
    ></select-product-dialog>

    <el-dialog
      title="库存明细"
      :visible.sync="dialogDetailsVisible"
      width="900px"
      append-to-body
      custom-class="custom-dialog" :close-on-click-modal="false"
    >
      <el-table :data="detailsList">
        <el-table-column label="发生时间" prop="createTime" width="180" />
        <el-table-column label="操作人" prop="createByName" />
        <el-table-column label="调整类型">
          <template slot-scope="scope">
            {{ scope.row.adjustType == 1 ? "入库" : "出库" }}
          </template>
        </el-table-column>
        <el-table-column label="库存增加">
          <template slot-scope="scope">
            {{ scope.row.adjustType == 1 ? "+" + scope.row.adjustNum : "" }}
          </template>
        </el-table-column>
        <el-table-column label="库存减少">
          <template slot-scope="scope">
            {{ scope.row.adjustType == 2 ? "-" + scope.row.adjustNum : "" }}
          </template>
        </el-table-column>
        <el-table-column label="剩余可用库存" prop="remainingNum" width="150" />
        <el-table-column label="备注" prop="remark" />
      </el-table>
      <pagination
        v-show="detailsTotal > 0"
        :total="detailsTotal"
        :page.sync="detailsParams.pageNum"
        :limit.sync="detailsParams.pageSize"
        @pagination="getDetailsList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getStoreStockListAPI,
  addStoreStockAPI,
  updateStoreStockAPI,
  delStoreStock,
  getStockDetailsAPI,
} from "@/api/system/member";
import { getGoodsDetailList, systemGoodsAPI } from "@/api/system/product";
import { getStoreList } from "@/api/system/store";
import SelectProductDialog from "@/components/Product/SelectProductDialog.vue";
import { mapGetters, mapState } from "vuex";
export default {
  components: {
    SelectProductDialog,
  },
  computed: {
    ...mapGetters(["roles", "storeId"]),
  },
  dicts: ["stock_type"],
  data() {
    return {
      loading: false,
      ids: [],
      roleList: [],
      total: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        storeId: undefined,
      },
      options: [],
      dialogVisible: false,
      form: {
        storeId: "",
        stockNum: "",
        remark: "",
        changeType: "1",
        goodsId: [],
      },
      rules: {
        storeId: [
          {
            required: true,
            message: "请选择门店",
            trigger: "blur",
          },
        ],
        stockNum: [
          {
            required: true,
            message: "请输入变化数量,限输入5个字符",
            trigger: "blur",
          },
        ],
      },
      dialogDetailsVisible: false,
      detailsList: [],
      detailsTotal: 0,
      detailsParams: {
        pageNum: 1,
        pageSize: 15,
      },
      disabled: false,
      selectProductList: [],
      stockNum: 0,
    };
  },
  created() {
    this.disabled = this.roles.some((item) => {
      return item != "admin";
    });
    if (this.storeId != null) {
      this.queryParams.storeId = this.storeId;
    }
    this.getStore();
    this.getList();
  },
  methods: {
    getGoodsDetail(row) {
      console.log("row: ", row);
      let obj = {
        goodsId: row.goodsId,
        storeId: row.storeId,
      };
      systemGoodsAPI(obj).then((res) => {
        if (res.code == 200) {
          this.selectProductList = [{ ...res.data }];
          this.stockNum = res.data.stockNum;
        }
      });
    },
    updstore(dict, value) {
      const match = dict.find((item) => item.value == value);
      return match ? match.label : "";
    },
    getStore() {
      getStoreList().then((response) => {
        this.options = response.rows;
      });
    },
    getList() {
      this.loading = true;
      getStoreStockListAPI(this.queryParams).then((response) => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDetailsList(row) {
      getStockDetailsAPI({ goodsId: row.goodsId, storeId: row.storeId }).then(
        (response) => {
          if (response.code == 200) {
            this.detailsList = response.rows;
            this.detailsTotal = response.total;
          }
        }
      );
    },
    openInventoryDialog(row) {
      this.dialogDetailsVisible = true;
      this.getDetailsList(row);
    },
    openSelectProduct() {
      if (this.form.storeId == "") {
        this.$message.warning("请选择门店");
        return;
      }
      this.$refs.selectProductRef.openSelectProduct();
    },
    handleSelectProduct(row) {
      console.log(row, "选择了");
      if (this.selectProductList?.length) {
        this.$message.warning("1次只能操作1个商品");
        return;
      }
      let obj = {
        goodsId: row.id,
        storeId: this.form.storeId,
      };
      systemGoodsAPI(obj).then((res) => {
        if (res.code == 200) {
          this.selectProductList.push(res.data);
          this.$refs.selectProductRef?.close();
          this.stockNum = res.data.stockNum;
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    handleRemove(row) {
      const matchIndex = this.selectProductList.findIndex(
        (item) => item.id === row.id
      );
      this.selectProductList.splice(matchIndex, 1);
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId);
    },

    handleDelete(row) {
      this.$confirm("确定删除该条数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delStoreStock(row.id).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("操作成功");
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleAdd() {
      this.dialogVisible = true;
      this.form = {
        storeId: "",
        stockNum: "",
        remark: "",
        changeType: "1",
        goodsId: [],
      };
      this.selectProductList = [];
      this.stockNum = 0;
      // 店长登录自动获取门店
      if (this.storeId != null) {
        this.form.storeId = this.storeId;
        // this.$nextTick(() => {
        //   this.$refs.phoneInput.focus();
        // });
      }
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(row));
      this.getGoodsDetail(row);
    },
    closeDialog() {
      this.dialogVisible = false;
      this.resetForm("dialogFormRef");
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid, errorObj) => {
        if (valid) {
          if (this.selectProductList?.length == 0) {
            this.$message.warning("请选择商品");
            return;
          }

          this.form.goodsId = this.selectProductList[0]?.id;
          if (this.form.id != undefined) {
            updateStoreStockAPI(this.form).then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess("操作成功");
                this.closeDialog();
                this.getList();
              }
            });
          } else {
            addStoreStockAPI(this.form).then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess("操作成功");
                this.closeDialog();
                this.getList();
              }
            });
          }
        }
      });
    },
  },
};
</script>
